﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using DevExpress.XtraPrinting;
using System.Data;
using DevExpress.XtraReports.UI;

namespace EnterpriseFund.Controllers
{
    // [OutputCache(Duration = 0, VaryByParam = "none")]
    public class QueryZDController : Controller
    {
        //
        // GET: /QueryZD/
        //  [AuthorityActionFilter("m_QueryZD", Order = 1)]
        //   [LogPageActionFilter("重点税源分月情况表", Order = 2)]
        public ActionResult Index()
        {
            BLL.Common commonBLL = new BLL.Common();
            DataSet yds = commonBLL.GetYear();
            List<SelectListItem> yearList = new List<SelectListItem>();
            for (int i = 0; i < yds.Tables[0].Rows.Count; i++)
            {
                yearList.Add(new SelectListItem() { Text = yds.Tables[0].Rows[i]["FYear"].ToString(), Value = yds.Tables[0].Rows[i]["FYear"].ToString() });
            }

            ViewData["YearData"] = yearList;
            string year = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);
            ViewData["year"] = year;
            return View();

        }
        public ActionResult QueryZDListPartial()
        {
            DataTable dt = GetModelVSBZSXX();

            return View(dt);

        }
        public ActionResult Print()
        {

            if (OperateSession.GetFromCache("QueryZD") == null)
            {
                Response.Write("<script>alert('当前请求打印数据不存在') ;window.close();</script>");
            }
            else
            {

                return View("Print");
            }
            return View("Print");
        }
        public ActionResult ReportViewerPartial()
        {

            var zsxx = GetModelVSBZSXX();

            zsxx.Columns.Remove("NSRDZDAH");
            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryZD") as MVCxGridViewState, zsxx);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;

            this.ViewData["rpt"] = report;

            return PartialView("ReportViewerPartial");

        }
        void generator_CustomizeColumnsCollection(object source, ColumnsCreationEventArgs e)
        {


            for (int i = 0; i < e.ColumnsInfo.Count; i++)
            {

                if (e.ColumnsInfo[i].FieldName == "FFileNo")
                {
                    e.ColumnsInfo[i].ColumnWidth = 60;
                }
                if (e.ColumnsInfo[i].FieldName == "FIssueNo")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRSBH")
                {
                    e.ColumnsInfo[i].ColumnWidth = 320;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRBM")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }

                if (e.ColumnsInfo[i].FieldName == "NSRMC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 320;
                }

                if (e.ColumnsInfo[i].FieldName == "FFinancePropShortName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "FAmount")
                {
                    e.ColumnsInfo[i].ColumnWidth = 140;
                }
                if (e.ColumnsInfo[i].FieldName == "FFileName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 250;
                }
            }

        }
        void generator_CustomizeColumn(object source, ControlCustomizationEventArgs e)
        {
            if (e.FieldName == "montbnew")
            {

                XRTableCell c = e.Owner as XRTableCell;

            }

            if (e.FieldName == "yrtbnew")
            {

                XRTableCell c = e.Owner as XRTableCell;



            }
            if (e.FieldName == "NSRMC")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleLeft;

            }
        }


        private DataTable GetModelVSBZSXX()
        {
            BLL.SB_ZSXX SB_ZSXXBLL = new BLL.SB_ZSXX();
            var Fyear = Request["Fyear"];
            var Fmon = Request["Fmon"];
            string dtime = Fyear.ToString() + Fmon.ToString().PadLeft(2, '0') + "01";
            DataTable dt = SB_ZSXXBLL.GetQueryZD(dtime, "");
            Rounddt(dt);
            return dt;
        }
        public System.Web.Mvc.FileResult ToExecl(DataTable showData)
        {
            try
            {
                showData.Columns.Remove("NSRDZDAH");
                DataRow hjdr = showData.NewRow();
                foreach (DataColumn dc in showData.Columns)
                {
                    if (dc.DataType == typeof(decimal) & !dc.ColumnName.Contains("NSRSBH"))
                    {
                        hjdr[dc.ColumnName] = showData.Compute("sum([" + dc.ColumnName + "])", "");
                    }
                    if (dc.ColumnName == "NSRMC")
                    {
                        hjdr["NSRMC"] = "合计";
                    }
                }
                showData.Rows.Add(hjdr);
                int totalRowCount = 1;
                List<Model.XlsModel> xlsModelList = new List<Model.XlsModel>();
                Model.XlsModel xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 12;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "单位：万元";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Right;
                xlsModelList.Add(xlsModel);
                totalRowCount++;
                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "序号";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);
                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "企业名称";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "纳税代码";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "1.增值税";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "2.消费税";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "3.营业税";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "4.企业所得税";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "5.个人所得税";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "6.其他税收";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "1-6.税收收入小计";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);
                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "7.教育费附加";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);
                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 1;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "1-7.财政收入合计";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Center;
                xlsModelList.Add(xlsModel);

                for (int i = 0; i < showData.Rows.Count; i++)
                {
                    totalRowCount++;
                    int colcount = 0;
                    foreach (System.Data.DataColumn dc in showData.Columns)
                    {
                        colcount++;
                        if (!string.IsNullOrEmpty(showData.Rows[i][dc.ColumnName].ToString()))
                        {
                            xlsModel = new Model.XlsModel();
                            xlsModel.ColSpan = 1;
                            xlsModel.RowIndex = totalRowCount;
                            xlsModel.Title = showData.Rows[i][dc.ColumnName].ToString();
                            if (colcount == 2 | colcount == 3)
                            {
                                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Left;
                            }
                            else
                            {
                                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Right;
                            }
                            xlsModelList.Add(xlsModel);
                        }
                        else
                        {
                            xlsModel = new Model.XlsModel();
                            xlsModel.ColSpan = 1;
                            xlsModel.RowIndex = totalRowCount;
                            xlsModel.Title = "";
                            if (colcount == 2 | colcount == 3)
                            {
                                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Left;
                            }
                            else
                            {
                                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Right;
                            }
                            xlsModelList.Add(xlsModel);
                        }
                    }
                }
                totalRowCount++;
                xlsModel = new Model.XlsModel();
                xlsModel.ColSpan = 12;
                xlsModel.RowIndex = totalRowCount;
                xlsModel.Title = "注：大榭石化数据为企业缴纳数，增值税（含成品油划中央库3.6％部分），其他税收（城建税含成品油划中央库6.9%部分）,教育费附加（含成品油划中央库3.0%部分）。";
                xlsModel.HAlign = Model.XlsModel.HorizontalAlign.Left;
                xlsModelList.Add(xlsModel);

                List<Model.XlsModel_Column> xlsModelColumns = new List<Model.XlsModel_Column>();
                xlsModelColumns.Add(new Model.XlsModel_Column()
                {
                    ColumnIndexStart = 0,
                    ColumnIndexEnd = 1,
                    Width = 10
                });
                xlsModelColumns.Add(new Model.XlsModel_Column()
                {
                    ColumnIndexStart = 1,
                    ColumnIndexEnd = 2,
                    Width = 45
                });
                xlsModelColumns.Add(new Model.XlsModel_Column()
                {
                    ColumnIndexStart = 2,
                    ColumnIndexEnd = 3,
                    Width = 30
                });
                xlsModelColumns.Add(new Model.XlsModel_Column()
                {
                    ColumnIndexStart = 3,
                    ColumnIndexEnd = 12,
                    Width = 15
                });
                List<Model.XlsModel_Row> xlsModelRows = new List<Model.XlsModel_Row>();
                ushort rowCount = (ushort)(totalRowCount);
                xlsModelRows.Add(new Model.XlsModel_Row()
                {
                    RowIndexStart = 1,
                    RowIndexEnd = 1,
                    RowHeight = 23
                });
                xlsModelRows.Add(new Model.XlsModel_Row()
                {
                    RowIndexStart = 2,
                    RowIndexEnd = rowCount,
                    RowHeight = 15

                });
                Model.ExcelTitleFont excelTitleFont = new Model.ExcelTitleFont()
                {
                    FontName = "宋体",
                    FontSize = 18,
                    Bold = true
                };
                var Year = Fetch.Post("hFyear");
                var Mon = Fetch.Post("hFmon");
                byte[] b = Common.ExcelClass.ExportToExcelReturnByte("", Year + "年" + int.Parse(Mon) + "月大榭开发区重点税源企业缴纳财政收入情况表", Year + "年" + int.Parse(Mon) + "月大榭开发区重点税源企业缴纳财政收入情况表", excelTitleFont, totalRowCount, xlsModelList, xlsModelColumns, xlsModelRows);

                string name = Year + "年" + int.Parse(Mon) + "月大榭开发区重点税源企业税收收入情况表.xls";
                return File(b, "application/vnd.ms-excel", HttpUtility.UrlEncode(name));

            }
            catch (System.Exception ex)
            {
                return null;
            }
        }
        public ActionResult ExportToXls()
        {
            var table = GetModelVSBZSXXFetch();
            return ToExecl(table);
            // return GridViewExtension.ExportToXls(ExportGridViewSettings, table, HttpUtility.UrlEncode("重点税源分月缴纳财政收入情况表导出.xls"), true);
        }
        private DataTable GetModelVSBZSXXFetch()
        {
            BLL.SB_ZSXX SB_ZSXXBLL = new BLL.SB_ZSXX();
            //var Fyear = ComboBoxExtension.GetValue<string>("Fyear");
            //var Fmon = ComboBoxExtension.GetValue<string>("Fmon");

            //根据隐藏字段 

            var Fyear = Fetch.Post("hFyear");
            var Fmon = Fetch.Post("hFmon");
            string dtime = Fyear.ToString() + Fmon.ToString().PadLeft(2, '0') + "01";
            DataTable dt = SB_ZSXXBLL.GetQueryZD(dtime, "");
            Rounddt(dt);
            return dt;
        }
        private static void Rounddt(DataTable dt)
        {

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                dt.Rows[i]["jzs"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["jzs"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["jzs"].ToString()) / 10000), 2);
                dt.Rows[i]["xfs"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["xfs"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["xfs"].ToString()) / 10000), 2);
                dt.Rows[i]["yys"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["yys"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["yys"].ToString()) / 10000), 2);
                dt.Rows[i]["qys"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["qys"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["qys"].ToString()) / 10000), 2);
                dt.Rows[i]["grs"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["grs"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["grs"].ToString()) / 10000), 2);
                dt.Rows[i]["qts"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["qts"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["qts"].ToString()) / 10000), 2);
                dt.Rows[i]["xj"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["xj"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["xj"].ToString()) / 10000), 2);
                dt.Rows[i]["jyfj"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["jyfj"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["jyfj"].ToString()) / 10000), 2);
                dt.Rows[i]["qb"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["qb"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["qb"].ToString()) / 10000), 2);

            }
        }
        static GridViewSettings exportGridViewSettings;
        public static GridViewSettings ExportGridViewSettings
        {

            get
            {

                if (exportGridViewSettings == null)

                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }

        public static GridViewSettings CreateExportGridViewSettings()
        {
            var setting = new GridViewSettings();
            setting.Name = "gvEditing";
            setting.KeyFieldName = "NSRDZDAH";
            setting.CallbackRouteValues = new { Controller = "QueryZD", Action = "QueryZDListPartial" };
            setting.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            setting.SettingsPager.PageSize = EnterpriseFund.Common.GlobalConstant.CONSTRING_PAGESIZE;
            setting.Columns.Add("xh", "序号");

            setting.Columns.Add("NSRMC", "企业名称");
            setting.Columns.Add("NSRSBH", "纳税代码");
            setting.Columns.Add("jzs", "1.增值税");
            setting.Columns.Add("xfs", "2.消费税");
            setting.Columns.Add("yys", "3.营业税");

            setting.Columns.Add("qys", "4.企业所得税");
            setting.Columns.Add("grs", "5.个人所得税");
            setting.Columns.Add("qts", "6.其他税收");
            setting.Columns.Add("xj", "1-6.小计");
            setting.Columns.Add("jyfj", "7.教育费附加税");
            setting.Columns.Add("qb", "1-7.财政收入合计");

            setting.SettingsBehavior.AllowFocusedRow = true;
            setting.SettingsLoadingPanel.Text = "数据读取中...";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRMC").DisplayFormat = "总计:";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "jzs").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "xfs").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "yys").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "qys").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "grs").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "qts").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "xj").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "jyfj").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "qb").DisplayFormat = "￥{0}";
            setting.Settings.ShowGroupPanel = true;
            setting.Settings.ShowFooter = true;
            setting.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
            setting.ClientSideEvents.EndCallback = "function(){}";
            setting.SettingsBehavior.EnableCustomizationWindow = true;
            setting.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }
            };
            setting.SettingsExport.RenderBrick = (sender, e) =>
            {
                if (e.Column.Caption.Contains("纳税代码"))
                {

                    e.TextValueFormatString = "{0}";
                }
            };
            setting.PreRender = setting.BeforeGetCallbackResult = (sender, e) =>
            {


                MVCxGridView gridView = sender as MVCxGridView;
                MVCxGridViewState gridViewState = new MVCxGridViewState(gridView);
                OperateSession.SetToCache(gridViewState, "QueryZD");


            };
            return setting;
        }





    }
}
